package com.yanqu.road.server.gameplayer.module.activity.busyfarming;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.busyfarming.*;
import com.yanqu.road.entity.activity.busyfarming.enums.eBusyFarmingLandState;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eSexType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.location.LocationInfo;
import com.yanqu.road.entity.log.*;
import com.yanqu.road.entity.player.UserBagItem;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.relatives.RelativesInfo;
import com.yanqu.road.entity.union.cross.CrossUnionInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.pb.activity.BusyFarmingProto;
import com.yanqu.road.pb.player.PlayerProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.BagModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.relatives.RelativesModule;
import com.yanqu.road.server.manger.DecorationMgr;
import com.yanqu.road.server.manger.NameMgr;
import com.yanqu.road.server.manger.ServerLanguageMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.busyfarming.BusyFarmingMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.config.TitleMgr;
import com.yanqu.road.server.manger.location.LocationMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.relatives.RelativesMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class BusyFarmingModule extends GeneralModule {

    //随机到的待偷取列表
    public List<BusyFarmingProto.CrossBusyFarmingStealDataTemp> stealSearchTempList;
    //偷取界面详情请求验证码
    public int GOTO_STEAL_DETAIL_CSRF_CODE = 0;
    //已偷取的地块
    public Set<Integer> stolenLandList = new HashSet<>();
    //待偷取数据
    public BusyFarmingProto.BusyFarmingUserDataTemp.Builder stealTempData;

    RandomHelper randomHelper = new RandomHelper();

    //已偷取玩家缓存
    Map<Long, Integer> stolenUserMap = new ConcurrentHashMap<>();

  public BusyFarmingModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
        int activityId = BusyFarmingMgr.getShowTimeActivityId();
        if (activityId != 0 && SystemOpenMgr.systemOpen(player, eSystemId.BusyFarmingActivity.getValue())) {
            BusyFarmingUserData userData = BusyFarmingMgr.getBusyFarmingUserData(player.getUserId());
            if (userData == null) {
                initUserData();
            }
        }
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public void afterLogin() {
        dailyReset();
        syncUserData();
        checkRedDot();
    }

    @Override
    public boolean saveData() {
        return true;
    }

    public BusyFarmingUserData getUserData() {
        return BusyFarmingMgr.getBusyFarmingUserData(player.getUserId());
    }

    public void dailyReset() {
        if(BusyFarmingMgr.getShowTimeActivityId() > 0) {
            BusyFarmingUserData userData = BusyFarmingMgr.getBusyFarmingUserData(player.getUserId());
            BusyFarmingMgr.dailyReset(userData);
        }
    }

    public void initUserData() {
        int showTimeActivityId = BusyFarmingMgr.getShowTimeActivityId();
        if(showTimeActivityId == 0){
            return;
        }
        ActivityInfo activityInfo = BusyFarmingMgr.getActivityInfo();
        if (!ActivityMgr.activityInShowTime(activityInfo)) {
            return;
        }
        BusyFarmingUserData userData = BusyFarmingMgr.getBusyFarmingUserData(player.getUserId());
        if(userData == null || (userData.getActivityId() != showTimeActivityId && showTimeActivityId > 0)) {
            BusyFarmingUserData tempUserData = new BusyFarmingUserData();
            tempUserData.setActivityId(showTimeActivityId);
            tempUserData.setUserId(player.getUserId());
            tempUserData.setInsertOption();
            tempUserData.setHomeGrade(1);

            //地块初始化
            for(int i = 0; i < BusyFarmingMgr.ALL_LAND_NUM; i++){
                BusyFarmingLand land = new BusyFarmingLand();
                land.setId(i);
                if(i < BusyFarmingMgr.UN_LOCKED_LAND_NUM){
                    land.getStates().add(eBusyFarmingLandState.Plant.getIntValue());
                }else {
                    land.getStates().add(eBusyFarmingLandState.Lock.getIntValue());
                }
                tempUserData.getLandMap().put(i, land);
            }
            BusyFarmingMgr.getUserDataMap().put(player.getUserId(), tempUserData);
            gift();
        }
    }

    /**
     * 赠送
     */
    private void gift() {
        try {
            //赠送草莓种子+肥料
            int seedId = BusyFarmingMgr.getBusyFarmingSeedGoods().get(0);
            player.getModule(CurrencyModule.class).addCurrency(seedId + "=1", eLogMoneyType.BusyFarmingActivity, eLogMoneyType.BusyFarmingActivityGoodsGive);
            int time = BusyFarmingMgr.getSeedMaturityTime(seedId);
            GoodsInfo goodsInfo = GoodsMgr.getGoodsById(BusyFarmingMgr.BUSY_FARMING_MANURE_ID);
            int perTime = goodsInfo.getParamList().get(0).intValue();
            int num = (int)Math.ceil(time / perTime);
            player.getModule(CurrencyModule.class).addCurrency(BusyFarmingMgr.BUSY_FARMING_MANURE_ID + "=" + num, eLogMoneyType.BusyFarmingActivity, eLogMoneyType.BusyFarmingActivityGoodsGive);
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }
    }

    public void syncUserData() {
        BusyFarmingUserData userData = BusyFarmingMgr.getBusyFarmingUserData(player.getUserId());
        if(userData == null){
            return;
        }
        BusyFarmingProto.BusyFarmingUserDataSyncMsg.Builder syncMsg = BusyFarmingProto.BusyFarmingUserDataSyncMsg.newBuilder();
        BusyFarmingProto.BusyFarmingUserDataTemp.Builder dataBuilder = BusyFarmingPb.getUserDataBuilder(userData, true);
        syncMsg.setActivityId(BusyFarmingMgr.getShowTimeActivityId());
        syncMsg.setUserData(dataBuilder);
        syncMsg.setConfig(BusyFarmingPb.getBusyFarmingConfigDataTempBuilder(player.getLanguage()));
        player.sendPacket(Protocol.U_BUSY_FARMING_USER_DATA_SYNC, syncMsg);
    }

    /**
     * 检查红点数据
     */
    private void checkRedDot() {
        try {
            long userId = player.getUserId();
            BusyFarmingUserData userData = BusyFarmingMgr.getBusyFarmingUserData(userId);
            if (userData == null) {
                return;
            }
            int val = 0, type = 0;
            List<BusyFarmingHelpRecord> helpList = BusyFarmingMgr.getUserHelpRecord(userId);
            if (helpList.size() > 0) {
                BusyFarmingHelpRecord record = helpList.get(helpList.size() - 1);
                if (!record.isReaded()) {
                    val = val | 1;
                    type = type | 1;
                }
            }
            List<BusyFarmingStolenRecord> stolenList = BusyFarmingMgr.getUserStolenRecord(userId);
            if (stolenList.size() > 0) {
                BusyFarmingStolenRecord record = stolenList.get(stolenList.size() - 1);
                if (!record.isReaded()) {
                    val = val | 2;
                    type = type | 2;
                }
            }
            List<BusyFarmingUserReward> rewardList = BusyFarmingMgr.getUserReward(userId);
            for(BusyFarmingUserReward reward : rewardList){
                if(!reward.isGetReward()){
                    val = val | 4;
                    type = type | 4;
                    break;
                }
            }
            if(BusyFarmingMgr.landHasState(userData, eBusyFarmingLandState.Harvest.getIntValue())){
                val = val | 8;
                type = type | 8;
            }
            syncRedDot(type, val);
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 种植
     */
    public int plant(int landId, int goodsId) {
        BusyFarmingUserData userData = BusyFarmingMgr.getBusyFarmingUserData(player.getUserId());
        if(userData == null){
            return GameErrorCode.E_BUSY_FARMING_ACTIVITY_NO_UNLOCK;
        }

        BusyFarmingLand land = userData.getLandMap().get(landId);
        synchronized (userData) {
            if(land.getStates().contains(eBusyFarmingLandState.Lock.getIntValue())){
                return GameErrorCode.E_BUSY_FARMING_ACTIVITY_LAND_NO_UNLOCK;
            }

            if(!land.getStates().contains(eBusyFarmingLandState.Plant.getIntValue())){
                return GameErrorCode.E_BUSY_FARMING_ACTIVITY_UN_PLANT;
            }

            Property property = PropertyHelper.parseStringToProperty(goodsId + "=1");
            if (!player.getModule(CurrencyModule.class).removeCurrency(property, eLogMoneyType.BusyFarmingActivity, eLogMoneyType.BusyFarmingActivityUseGoods)) {
                return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
            }
            land.setGoodsId(goodsId);
            land.setTotalTime(BusyFarmingMgr.getSeedMaturityTime(goodsId));
            land.setHarvestTime(DateHelper.getCurrentSecond() + 60 * land.getTotalTime());
            land.getStates().remove(eBusyFarmingLandState.Plant.getIntValue());
            land.getStates().add(eBusyFarmingLandState.Manure.getIntValue());
            userData.setUpdateOption();

            //种植日志
            LogBusyFarmingPlant logBusyFarmingPlant = new LogBusyFarmingPlant(BusyFarmingMgr.getShowTimeActivityId(), player.getUserId(), landId, goodsId, System.currentTimeMillis());
            LogMgr.addLogBusyFarmingPlant(logBusyFarmingPlant);
        }
        BusyFarmingProto.BusyFarmingPlantRespMsg.Builder respMsg  = BusyFarmingProto.BusyFarmingPlantRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setLand(BusyFarmingPb.getLandBuilder(land));
        player.sendPacket(Protocol.U_BUSY_FARMING_PLANT, respMsg);
        return 0;
    }

    /**
     * 解锁地块
     */
    public int openLand(int landId) {
        BusyFarmingUserData userData = BusyFarmingMgr.getBusyFarmingUserData(player.getUserId());
        if(userData == null){
            return GameErrorCode.E_BUSY_FARMING_ACTIVITY_NO_UNLOCK;
        }

        BusyFarmingLand land = userData.getLandMap().get(landId);
        synchronized (userData) {
            //检查是否按顺序解锁（防前端参数传错）
            BusyFarmingLand preLand = userData.getLandMap().get(landId - 1);
            if(preLand != null && preLand.getStates().contains(eBusyFarmingLandState.Lock.getIntValue())){
                return GameErrorCode.E_REQUEST_ARGUMENT_ERROR;
            }
            if(!land.getStates().contains(eBusyFarmingLandState.Lock.getIntValue())){
                return GameErrorCode.E_BUSY_FARMING_ACTIVITY_HAD_UNLOCK;
            }

            int idx = landId - BusyFarmingMgr.UN_LOCKED_LAND_NUM;
            if(idx < 0 || idx >= BusyFarmingMgr.BUSY_FARMING_LAND_OPEN_CONSUME.size()){
                return GameErrorCode.E_REQUEST_ARGUMENT_ERROR;
            }
            int num = BusyFarmingMgr.BUSY_FARMING_LAND_OPEN_CONSUME.get(idx);

            String consume = GameConfig.GAME_MONEY_INGOTS + "=" + num;

            if (!player.getModule(CurrencyModule.class).removeCurrency(PropertyHelper.parseStringToProperty(consume), eLogMoneyType.BusyFarmingActivity, eLogMoneyType.BusyFarmingActivityUseGoods)) {
                return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
            }

            land.getStates().remove(eBusyFarmingLandState.Lock.getIntValue());
            land.getStates().add(eBusyFarmingLandState.Plant.getIntValue());
            userData.setUpdateOption();

            //土地购买日志
            LogBusyFarmingLandBuy logBusyFarmingLandBuy = new LogBusyFarmingLandBuy(BusyFarmingMgr.getShowTimeActivityId(), player.getUserId(), landId, num, System.currentTimeMillis());
            LogMgr.addLogBusyFarmingLandBuy(logBusyFarmingLandBuy);
        }

        BusyFarmingProto.BusyFarmingLandOpenRespMsg.Builder respMsg  = BusyFarmingProto.BusyFarmingLandOpenRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setLand(BusyFarmingPb.getLandBuilder(land));
        player.sendPacket(Protocol.U_BUSY_FARMING_LAND_OPEN, respMsg);
        return 0;
    }

    /**
     * 施肥
     */
    public int manure(int landId, int goodsId) {
        BusyFarmingUserData userData = BusyFarmingMgr.getBusyFarmingUserData(player.getUserId());
        if(userData == null){
            return GameErrorCode.E_BUSY_FARMING_ACTIVITY_NO_UNLOCK;
        }
        BusyFarmingLand land = userData.getLandMap().get(landId);

        synchronized (userData){

            int nowTime = DateHelper.getCurrentSecond();
            BusyFarmingMgr.calLandState(land, nowTime);

            if(land.getStates().contains(eBusyFarmingLandState.Harvest.getIntValue()) || !land.getStates().contains(eBusyFarmingLandState.Manure.getIntValue())){
                return GameErrorCode.E_BUSY_FARMING_ACTIVITY_NO_NEED_MANURE;
            }

            Property property = PropertyHelper.parseStringToProperty(goodsId + "=1");
            if (!player.getModule(CurrencyModule.class).removeCurrency(property, eLogMoneyType.BusyFarmingActivity, eLogMoneyType.BusyFarmingActivityUseGoods)) {
                return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
            }

            int harvestTime = land.getHarvestTime();
            int subTime = BusyFarmingMgr.getFertilizerQuickenTime(goodsId) * 60;
            harvestTime -= subTime;
            land.setHarvestTime(harvestTime);
            land.setQuickenTimes(1 + land.getQuickenTimes());
            BusyFarmingMgr.calLandState(land, nowTime);
            userData.setUpdateOption();

            //收获红点
            if(BusyFarmingMgr.landHasState(userData, eBusyFarmingLandState.Harvest.getIntValue())){
                syncRedDot(8, 8);
            }

            //施肥日志
            long harvestTime1 = 1000 * (long)land.getHarvestTime();
            LogBusyFarmingQuicken quickenLog = new LogBusyFarmingQuicken(BusyFarmingMgr.getShowTimeActivityId(), player.getUserId(), landId, land.getGoodsId(), 1, harvestTime1, System.currentTimeMillis());
            LogMgr.addLogBusyFarmingQuicken(quickenLog);

            BusyFarmingProto.BusyFarmingQuickenRespMsg.Builder respMsg = BusyFarmingProto.BusyFarmingQuickenRespMsg.newBuilder();
            respMsg.setRet(0);
            respMsg.setNum(1);
            respMsg.setLand(BusyFarmingPb.getLandBuilder(land));
            player.sendPacket(Protocol.U_BUSY_FARMING_QUICKEN_GROWS, respMsg);
        }
        return 0;
    }

    /**
     * 一键施肥
     */
    public int oneKeyManure(int landId, int goodsId) {
        BusyFarmingUserData userData = BusyFarmingMgr.getBusyFarmingUserData(player.getUserId());
        if(userData == null){
            return GameErrorCode.E_BUSY_FARMING_ACTIVITY_NO_UNLOCK;
        }
        BusyFarmingLand land = userData.getLandMap().get(landId);

        synchronized (userData){

            //果园等级是否足够
            if(userData.getHomeGrade() < BusyFarmingMgr.BUSY_FARMING_ONE_KEY_MANURE_GRADE){
                return GameErrorCode.E_BUSY_FARMING_ACTIVITY_HOME_GRADE_NO_ENOUGH;
            }

            int nowTime = DateHelper.getCurrentSecond();
            BusyFarmingMgr.calLandState(land, nowTime);
            if(land.getStates().contains(eBusyFarmingLandState.Harvest.getIntValue()) || !land.getStates().contains(eBusyFarmingLandState.Manure.getIntValue())){
                return GameErrorCode.E_BUSY_FARMING_ACTIVITY_NO_NEED_MANURE;
            }

            // 离成熟还需时间
            int needTime = land.getHarvestTime() - nowTime;
            int perQuickenTime = BusyFarmingMgr.getFertilizerQuickenTime(goodsId) * 60;
            int need = needTime / perQuickenTime + 1;

            int ownCount = 0;
            UserBagItem userBagItem = player.getModule(BagModule.class).getUserBagItem(goodsId);
            if(userBagItem != null){
                ownCount = (int)userBagItem.getNum();
            }
            if(ownCount == 0){
                return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
            }
            if(ownCount < need){
                need = ownCount;
            }

            Property property = PropertyHelper.parseStringToProperty(goodsId + "=" + need);
            if (!player.getModule(CurrencyModule.class).removeCurrency(property, eLogMoneyType.BusyFarmingActivity, eLogMoneyType.BusyFarmingActivityUseGoods)) {
                return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
            }

            land.setHarvestTime(land.getHarvestTime() - need * perQuickenTime);
            land.setQuickenTimes(need + land.getQuickenTimes());
            BusyFarmingMgr.calLandState(land, nowTime);
            userData.setUpdateOption();

            BusyFarmingProto.BusyFarmingQuickenRespMsg.Builder respMsg = BusyFarmingProto.BusyFarmingQuickenRespMsg.newBuilder();
            respMsg.setRet(0);
            respMsg.setNum(need);
            respMsg.setLand(BusyFarmingPb.getLandBuilder(land));
            player.sendPacket(Protocol.U_BUSY_FARMING_ONE_KEY_QUICKEN_GROWS, respMsg);

            //收获红点
            if(BusyFarmingMgr.landHasState(userData, eBusyFarmingLandState.Harvest.getIntValue())){
                syncRedDot(8, 8);
            }

            //施肥日志
            long harvestTime = 1000 * (long)land.getHarvestTime();
            LogBusyFarmingQuicken quickenLog = new LogBusyFarmingQuicken(BusyFarmingMgr.getShowTimeActivityId(), player.getUserId(), landId, land.getGoodsId(), need, harvestTime, System.currentTimeMillis());
            LogMgr.addLogBusyFarmingQuicken(quickenLog);
        }
        return 0;
    }

    /**
     * 收获（获得积分与水果道具）
     */
    public int harvest(int landId) {
        BusyFarmingUserData userData = BusyFarmingMgr.getBusyFarmingUserData(player.getUserId());
        if(userData == null){
            return GameErrorCode.E_BUSY_FARMING_ACTIVITY_NO_UNLOCK;
        }
        BusyFarmingLand land = userData.getLandMap().get(landId);

        synchronized (userData){

            int nowTime = DateHelper.getCurrentSecond();
            BusyFarmingMgr.calLandState(land, nowTime);
            if(!land.getStates().contains(eBusyFarmingLandState.Harvest.getIntValue())){
                return GameErrorCode.E_BUSY_FARMING_ACTIVITY_NO_NEED_HARVEST;
            }

            Property reward = new Property();

            int num = BusyFarmingMgr.getSeedMaturityFruitNum(land.getGoodsId(), land.getWateringTimes());
            //减产
            for(int c : land.getReduce()){
                num -= c;
            }

            //收获水果积分
            int score = BusyFarmingMgr.getSeedMaturityFruitScore(land.getGoodsId()) * num;
            userData.setFruitScore(userData.getFruitScore() + score);
            //果园等级
            userData.setHomeGrade(BusyFarmingMgr.getGuoYuanGrade(userData.getFruitScore()));

            GoodsInfo fruit = BusyFarmingMgr.getSeedMaturityFruit(land.getGoodsId());
            reward.addProperty(fruit.getGoodsId(), BigInteger.valueOf(num));
            //收获水果道具
            player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.BusyFarmingActivity, eLogMoneyType.BusyFarmingActivityGetGoods);

            long harvestTime = (long)land.getHarvestTime() * 1000;

            land.getStates().clear();
            land.getStates().add(eBusyFarmingLandState.Plant.getIntValue());

            //排行榜
            player.notifyListener(eGamePlayerEventType.BusyFarmingScoreRank.getValue(), userData.getFruitScore());
            player.notifyListener(eGamePlayerEventType.BusyFarmingScoreCrossRank.getValue(), userData.getFruitScore());

            //成就
            player.notifyListener(eGamePlayerEventType.BusyFarmingGrade.getValue(), userData.getFruitScore());


            //收获日志
            LogBusyFarmingHarvest harvestLog = new LogBusyFarmingHarvest(BusyFarmingMgr.getShowTimeActivityId(), player.getUserId(), landId, land.getGoodsId(), num,
                    land.getQuickenTimes(), land.getWateringTimes(), land.getStolenTimes(), harvestTime, System.currentTimeMillis());
            LogMgr.addLogBusyFarmingHarvest(harvestLog);

            clearLandData(land);
            userData.setUpdateOption();

            BusyFarmingProto.BusyFarmingHarvestRespMsg.Builder respMsg = BusyFarmingProto.BusyFarmingHarvestRespMsg.newBuilder();
            respMsg.setLand(BusyFarmingPb.getLandBuilder(land));
            respMsg.setReward(PropertyHelper.parsePropertyToString(reward));
            respMsg.setUserData(BusyFarmingPb.getUserDataBuilder(userData, false));
            respMsg.setScore(score);
            respMsg.setRet(0);
            player.sendPacket(Protocol.U_BUSY_FARMING_HARVEST, respMsg);

        }

        if(BusyFarmingMgr.landHasState(userData, eBusyFarmingLandState.Harvest.getIntValue())){
            syncRedDot(8, 8);
        }else {
            syncRedDot(8, 0);
        }

        return 0;
    }

    /**
     * 收获、铲除,清数据
     */
    public void clearLandData(BusyFarmingLand land) {
        land.setGoodsId(0);
        land.setTotalTime(0);
        land.setHarvestTime(0);
        land.setWateringTimes(0);
        land.setStolenTimes(0);
        land.setQuickenTimes(0);
        land.getReduce().clear();
        land.setFlorescence(false);
    }

    /**
     * 浇水 (获得水果道具)
     */
    public int watering(int landId, long userId) {

        BusyFarmingUserData userData = BusyFarmingMgr.getBusyFarmingUserData(player.getUserId());
        BusyFarmingUserData friendUserData = BusyFarmingMgr.getBusyFarmingUserData(userId);
        if(userData == null || friendUserData == null){
            return GameErrorCode.E_BUSY_FARMING_ACTIVITY_NO_UNLOCK;
        }
        BusyFarmingLand land = friendUserData.getLandMap().get(landId);
        int nowTime = DateHelper.getCurrentSecond();

        List<Integer> wateringParams = BusyFarmingMgr.getBusyFarmingWateringParam();

        //来助酬谢
        BusyFarmingUserReward reward;
        //来助记录
        BusyFarmingHelpRecord record;
        synchronized (userData){
            //我的浇水次数
            if(userData.getWateringTimes() >= wateringParams.get(0)){
                return GameErrorCode.E_BUSY_FARMING_ACTIVITY_WATERING_HAD_LIMIT;
            }
            userData.setWateringTimes(userData.getWateringTimes() + 1);
            //来助酬谢
            reward = initUserReward(UserMgr.getUserInfo(userId), player.getUserId(), land.getGoodsId());
        }

        synchronized (friendUserData) {
            BusyFarmingMgr.calLandState(land, nowTime);
            if (!land.getStates().contains(eBusyFarmingLandState.Watering.getIntValue())) {
                userData.setWateringTimes(userData.getWateringTimes() - 1);
                return GameErrorCode.E_BUSY_FARMING_ACTIVITY_NO_NEED_WATERING;
            }
            //对方被浇水次数
            if(friendUserData.getBeWateringTimes() >= wateringParams.get(3)){
                userData.setWateringTimes(userData.getWateringTimes() - 1);
                return GameErrorCode.E_BUSY_FARMING_ACTIVITY_FRIEND_WATERING_HAD_LIMIT;
            }
            friendUserData.setBeWateringTimes(1 + friendUserData.getBeWateringTimes());

            //浇水+加产量
            land.setWateringTimes(1 + land.getWateringTimes());
            BusyFarmingMgr.calLandState(land, nowTime);
            friendUserData.setUpdateOption();

            GoodsInfo fruitGoods = BusyFarmingMgr.getSeedMaturityFruit(land.getGoodsId());
            int addition = 0;
            if(fruitGoods != null){
                addition = fruitGoods.getParamList().get(2).intValue();
            }
            //来助记录
            record = initHelpRecord(userId, player.getUserInfo(), land.getGoodsId(), addition);

            //来助红点
            GamePlayer gamePlayer = GamePlayerMgr.getOnlinePlayer(userId);
            if(gamePlayer != null){
                gamePlayer.getModule(BusyFarmingModule.class).syncRedDot(1, 1);
            }
        }

        synchronized (BusyFarmingMgr.getUserLocker(friendUserData.getUserId())){
            BusyFarmingMgr.addUserHelpRecord(record);

            //浇水日志
            LogBusyFarmingWatering wateringLog = new LogBusyFarmingWatering(BusyFarmingMgr.getShowTimeActivityId(), userId, landId, land.getGoodsId(), player.getUserId(), System.currentTimeMillis());
            LogMgr.addLogBusyFarmingWatering(wateringLog);
        }

        synchronized (BusyFarmingMgr.getUserLocker(userData.getUserId())) {
            BusyFarmingMgr.addUserReward(reward);
        }
        //酬谢红点
        syncRedDot(4, 4);

        syncOtherUserData(friendUserData, true);

        BusyFarmingProto.BusyFarmingWateringRespMsg.Builder respMsg = BusyFarmingProto.BusyFarmingWateringRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setWateringTimes(userData.getWateringTimes());
        respMsg.setBeWateringTimes(userData.getBeWateringTimes());
        respMsg.setLand(BusyFarmingPb.getLandBuilder(land));
        player.sendPacket(Protocol.U_BUSY_FARMING_WATERING, respMsg);

        return 0;
    }

    public int wateringBack(int activityId,  BusyFarmingProto.BusyFarmingLandTemp landTemp, long userId, UserBaseInfo friend){

        BusyFarmingUserData userData = BusyFarmingMgr.getBusyFarmingUserData(player.getUserId());

        //来助酬谢
        BusyFarmingUserReward reward;
        synchronized (userData){
            userData.setWateringTimes(userData.getWateringTimes() + 1);
            //来助酬谢
            reward = initUserReward(friend, userId, player.getUserId(), landTemp.getGoodsId());
        }

        synchronized (BusyFarmingMgr.getUserLocker(userData.getUserId())) {
            BusyFarmingMgr.addUserReward(reward);
        }
        //酬谢红点
        syncRedDot(4, 4);

        BusyFarmingProto.BusyFarmingWateringRespMsg.Builder respMsg = BusyFarmingProto.BusyFarmingWateringRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setWateringTimes(userData.getWateringTimes());
        respMsg.setBeWateringTimes(userData.getBeWateringTimes());
        respMsg.setLand(landTemp);
        player.sendPacket(Protocol.U_BUSY_FARMING_WATERING, respMsg);

        return 0;
    }
    /**
     *  对方在线，同步下玩家数据
     */
    public void syncOtherUserData(BusyFarmingUserData friendUserData, boolean containLand) {
        GamePlayer gamePlayer = GamePlayerMgr.getOnlinePlayer(friendUserData.getUserId());
        if(gamePlayer != null){
            BusyFarmingProto.BusyFarmingUserDataSyncMsg.Builder syncMsg = BusyFarmingProto.BusyFarmingUserDataSyncMsg.newBuilder();
            BusyFarmingProto.BusyFarmingUserDataTemp.Builder dataBuilder = BusyFarmingPb.getUserDataBuilder(friendUserData, containLand);
            syncMsg.setActivityId(BusyFarmingMgr.getShowTimeActivityId());
            syncMsg.setUserData(dataBuilder);
            syncMsg.setConfig(BusyFarmingPb.getBusyFarmingConfigDataTempBuilder(gamePlayer.getLanguage()));
            gamePlayer.sendPacket(Protocol.U_BUSY_FARMING_USER_DATA_SYNC, syncMsg);
        }
    }

    /**
     * 铲除地块上的花苗
     */
    public int removeLand(int landId) {
        BusyFarmingUserData userData = BusyFarmingMgr.getBusyFarmingUserData(player.getUserId());
        if(userData == null){
            return GameErrorCode.E_BUSY_FARMING_ACTIVITY_NO_UNLOCK;
        }
        BusyFarmingLand land = userData.getLandMap().get(landId);
        synchronized (userData){
            long harvestTime = (long)land.getHarvestTime() * 1000;
            land.getStates().clear();
            land.getStates().add(eBusyFarmingLandState.Plant.getIntValue());

            //铲除日志
            LogBusyFarmingRemove removeLog = new LogBusyFarmingRemove(BusyFarmingMgr.getShowTimeActivityId(), player.getUserId(), landId, land.getGoodsId(), harvestTime, System.currentTimeMillis());
            LogMgr.addLogBusyFarmingRemove(removeLog);

            clearLandData(land);
            userData.setUpdateOption();
        }
        BusyFarmingProto.BusyFarmingRemoveRespMsg.Builder respMsg = BusyFarmingProto.BusyFarmingRemoveRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setLand(BusyFarmingPb.getLandBuilder(land));
        player.sendPacket(Protocol.U_BUSY_FARMING_REMOVE_GOODS, respMsg);
        return 0;
    }

    /**
     * 亲友/商会 果园列表（带浇水状态）
     */
    public int friendHome(int type) {
        //我是否有浇水次数
        boolean myCanWatering = true;
        BusyFarmingUserData myData = getUserData();
        if(myData == null){
            return GameErrorCode.E_BUSY_FARMING_ACTIVITY_NO_UNLOCK;
        }
        //浇水次数达上限
        if(myData.getWateringTimes() >= BusyFarmingMgr.getBusyFarmingWateringParam().get(0)){
            myCanWatering = false;
        }
        List<Long> friendList = new ArrayList<>();
        if(type == 1){
            boolean hasCrossFriend = false;
            //亲家
            Map<Long, RelativesInfo> relativesInfoMap = player.getModule(RelativesModule.class).getRelativesMap();
            for(Map.Entry<Long, RelativesInfo> entry : relativesInfoMap.entrySet()){
                RelativesInfo relativesInfo = entry.getValue();
                if(relativesInfo.getStatus() == 1) {
                    long relativesServerId = RelativesMgr.getUserServerId(entry.getKey());
                    if(relativesServerId != GameServer.getInstance().getServerId()){
                        hasCrossFriend = true;
                    }
                    friendList.add(entry.getKey());
                }
            }
            if(hasCrossFriend && friendList.size() > 0){
                BusyFarmingProto.BusyFarmingFriendHomeListCrossReqMsg.Builder crossReq = BusyFarmingProto.BusyFarmingFriendHomeListCrossReqMsg.newBuilder();
                crossReq.setType(type);
                for (Long fid : friendList) {
                    crossReq.addUser(BusyFarmingProto.BusyFarmingFriendId.newBuilder().setServerId(RelativesMgr.getUserServerId(fid)).setUserId(fid));
                }
                crossReq.setWateringLimit(BusyFarmingMgr.getBusyFarmingWateringParam().get(3));
                crossReq.setCanWatering(myCanWatering);
                crossReq.setActivityId(BusyFarmingMgr.getShowTimeActivityId());
                player.sendPacket(Protocol.C_BUSY_FARMING_FRIEND_HOME_LIST, crossReq);
                return 0;
            }
        }else {
            //跨服商会,直接上跨服
            CrossUnionInfo crossUnionInfo = CrossUnionMgr.getUnionInfo(player.getUserInfo().getUnionUid());
            if(crossUnionInfo != null && crossUnionInfo.isCross()){

                BusyFarmingProto.BusyFarmingFriendHomeListCrossReqMsg.Builder crossReq = BusyFarmingProto.BusyFarmingFriendHomeListCrossReqMsg.newBuilder();
                crossReq.setType(type);
                Map<Long, CrossUnionMember> memberMap = CrossUnionMgr.getUnionMemberMap(player.getUserInfo().getUnionUid());
                if(memberMap != null) {
                    for (CrossUnionMember member : memberMap.values()) {
                        if(member.getUserId() == player.getUserId()){
                            continue;
                        }
                        crossReq.addUser(BusyFarmingProto.BusyFarmingFriendId.newBuilder().setServerId(member.getServerId()).setUserId(member.getUserId()));
                    }
                }
                crossReq.setWateringLimit(BusyFarmingMgr.getBusyFarmingWateringParam().get(3));
                crossReq.setCanWatering(myCanWatering);
                crossReq.setActivityId(BusyFarmingMgr.getShowTimeActivityId());
                player.sendPacket(Protocol.C_BUSY_FARMING_FRIEND_HOME_LIST, crossReq);
                return 0;
            }
            //盟友
            Map<Long, CrossUnionMember> memberMap = CrossUnionMgr.getUnionMemberMap(player.getUserInfo().getUnionUid());
            if(memberMap != null){
                for(long uid : memberMap.keySet()){
                    friendList.add(uid);
                }
                friendList.remove(player.getUserId());
            }
        }

        BusyFarmingProto.BusyFarmingFriendHomeListRespMsg.Builder respMsg = BusyFarmingProto.BusyFarmingFriendHomeListRespMsg.newBuilder();
        respMsg.setType(type);
        for(long userId : friendList){
            BusyFarmingUserData userData = BusyFarmingMgr.getBusyFarmingUserData(userId);
            if(userData == null){
                continue;
            }
            boolean canWatering = myCanWatering && BusyFarmingMgr.canWatering(userData);
            respMsg.addFriend(BusyFarmingPb.getHomeTempBuilder(userData, canWatering, player.getUserInfo().getLanguage()));
        }
        player.sendPacket(Protocol.U_BUSY_FARMING_FRIEND_HOME_LIST, respMsg);
        return 0;
    }

    /**
     * 亲友/商会 果园详情
     */
    public int friendHomeDetail(long userId) {
        BusyFarmingUserData userData = BusyFarmingMgr.getBusyFarmingUserData(userId);
        if(userData == null){
            return GameErrorCode.E_BUSY_FARMING_ACTIVITY_NO_UNLOCK;
        }
        synchronized (userData){
            BusyFarmingMgr.calLandState(userData);
        }
        BusyFarmingProto.BusyFarmingFriendHomeDetailRespMsg.Builder respMsg = BusyFarmingProto.BusyFarmingFriendHomeDetailRespMsg.newBuilder();
        respMsg.setRet(0);
        BusyFarmingProto.BusyFarmingUserDataTemp.Builder userDataBuilder = BusyFarmingPb.getUserDataBuilder(userData, true);

        //判定浇水次数，强制设置成不可浇水
        BusyFarmingUserData myData = getUserData();
        if(myData != null){
            //我的浇水次数达上限 或者 对方被浇水次数达上限时
            if(myData.getWateringTimes() >= BusyFarmingMgr.getBusyFarmingWateringParam().get(0) || userData.getBeWateringTimes() >= BusyFarmingMgr.getBusyFarmingWateringParam().get(3)){
                userDataBuilder = BusyFarmingPb.getUserDataBuilder(userData, false);
                for (Map.Entry<Integer, BusyFarmingLand> landEntry : userData.getLandMap().entrySet()) {
                    BusyFarmingLand land = BusyFarmingMgr.cloneLand(landEntry.getValue());
                    if(land.getStates().contains(eBusyFarmingLandState.Watering.getIntValue())){
                        land.getStates().remove(eBusyFarmingLandState.Watering.getIntValue());
                    }
                    userDataBuilder.addLand(BusyFarmingPb.getLandBuilder(land));
                }
            }
        }
        UserBaseInfo userBaseInfo = UserMgr.getUserBaseInfo(userId, GameServer.getInstance().getServerId());
        userDataBuilder.setUserBaseInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
        userDataBuilder.setUserId(userId);

        respMsg.setFriend(userDataBuilder);
        player.sendPacket(Protocol.U_BUSY_FARMING_FRIEND_HOME_DETAIL, respMsg);
        return 0;
    }

    /**
     * 领取（酬谢）奖励，获得水果道具
     */
    public int getReward(long dbId) {
        BusyFarmingUserData userData = BusyFarmingMgr.getBusyFarmingUserData(player.getUserId());
        if(userData == null){
            return GameErrorCode.E_BUSY_FARMING_ACTIVITY_NO_UNLOCK;
        }
        List<BusyFarmingUserReward> todoList = new ArrayList<>();
        List<BusyFarmingUserReward> list = BusyFarmingMgr.getUserReward(player.getUserId());
        if(list != null){
            for(BusyFarmingUserReward userReward : list){
                if(dbId != 0){
                    if(userReward.getDbId() == dbId){
                        todoList.add(userReward);
                        break;
                    }
                }else {
                    if(userReward.isGetReward()){
                        continue;
                    }
                    todoList.add(userReward);
                }
            }
        }
        Property property = new Property();
        synchronized (userData) {
            for (BusyFarmingUserReward userReward : todoList) {
                if (userReward.isGetReward()) {
                    continue;
                }
                property.addProperty(PropertyHelper.parseStringToProperty(userReward.getReward()));
                userReward.setGetReward(true);
            }
            if(!property.isNothing()){
                //获取水果道具
                player.getModule(CurrencyModule.class).addCurrency(property, eLogMoneyType.BusyFarmingActivity, eLogMoneyType.BusyFarmingActivityGetGoods);
            }
        }
        BusyFarmingProto.BusyFarmingGetFriendRewardRespMsg.Builder respMsg = BusyFarmingProto.BusyFarmingGetFriendRewardRespMsg.newBuilder();
        respMsg.setDbId(dbId);
        respMsg.setRet(0);
        respMsg.setReward(PropertyHelper.parsePropertyToString(property));
        player.sendPacket(Protocol.U_BUSY_FARMING_FRIEND_GET_REWARD, respMsg);
        return 0;
    }

    /**
     * 系统解锁
     */
    public void initSystem() {
        initUserData();
        syncUserData();
    }

    /**
     * 清除缓存数据
     */
    public void clearStealCacheData(){
        //清除上次随机验证码
        GOTO_STEAL_DETAIL_CSRF_CODE = 0;
        //清除已偷取地块
        stolenLandList.clear();
        //清除随机数据（三选一）
        stealSearchTempList = null;
    }

    /**
     * 偷水果(获得水果奖励)
     */
    public int steal(int landId) {
        if(stealTempData == null){
            return GameErrorCode.E_BUSY_FARMING_ACTIVITY_STEAL_NO_DATA;
        }
        BusyFarmingProto.BusyFarmingLandTemp landTemp = stealTempData.getLand(landId);
        if(landTemp == null){
            return GameErrorCode.E_BUSY_FARMING_ACTIVITY_STEAL_NO_DATA;
        }
        if(landTemp.getGoodsId() == 0){
            return GameErrorCode.E_BUSY_FARMING_ACTIVITY_STEAL_LAND_NO_PLANT;
        }
        BusyFarmingUserData userData = getUserData();
        Property reward = new Property();
        //本服数据（被偷者如果是同一区服）
        BusyFarmingUserData stealUserData = null;
        int goodsId = landTemp.getGoodsId();
        int num;
        synchronized (userData){
            if(stolenLandList.contains(landId)){
                return GameErrorCode.E_BUSY_FARMING_ACTIVITY_STEAL_LAND_HAD_STOLEN;
            }
            //偷取的产量
            int radio = randomHelper.next(BusyFarmingMgr.getBusyFarmingStolenParam().get(2), BusyFarmingMgr.getBusyFarmingStolenParam().get(3));
            //log.info("steal radio {} beWateringTimes {}", radio, landTemp.getBeWateringTimes());
            num = BusyFarmingMgr.getStealRewardFruitNum(goodsId, landTemp.getBeWateringTimes(), radio);
            //log.info("steal num {}", num);
            GoodsInfo goodsInfo = BusyFarmingMgr.getSeedMaturityFruit(goodsId);
            if(goodsInfo == null){
                return GameErrorCode.E_GOODS_NO_EXIST;
            }
            reward.addProperty(goodsInfo.getGoodsId(), BigInteger.valueOf(num));
            player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.BusyFarmingActivity, eLogMoneyType.BusyFarmingActivityGetGoods);
            stolenLandList.add(landId);

            //非机器人才有失窃记录
            if(stealTempData.getUserId() > 10) {
                //失窃记录
                if (stealTempData.getUserBaseInfo().getServerId() != GameServer.getInstance().getServerId()) {
                    //上跨服中转
                    BusyFarmingProto.CrossBusyFarmingStealNotifyMsg.Builder notifyMsg = BusyFarmingProto.CrossBusyFarmingStealNotifyMsg.newBuilder();
                    notifyMsg.setActivityId(BusyFarmingMgr.getShowTimeActivityId());
                    notifyMsg.setUserId(stealTempData.getUserId());
                    notifyMsg.setServerId(stealTempData.getUserBaseInfo().getServerId());
                    notifyMsg.setLandId(landId);
                    notifyMsg.setSeedId(goodsId);
                    notifyMsg.setNum(num);
                    notifyMsg.setEnemyUserId(player.getUserId());
                    UserBaseInfo userBaseInfo = UserMgr.getUserBaseInfo(player.getUserId(), GameServer.getInstance().getServerId());
                    notifyMsg.setEnemy(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
                    player.sendPacket(Protocol.C_BUSY_FARMING_ACTIVITY_STEAL_NOTIFY, notifyMsg);
                } else {
                    //本区服被偷着
                    stealUserData = BusyFarmingMgr.getBusyFarmingUserData(stealTempData.getUserId());
                }
            }else {

                //偷取机器人日志
                LogBusyFarmingSteal stealLog = new LogBusyFarmingSteal(BusyFarmingMgr.getShowTimeActivityId(), player.getUserId(), landTemp.getId(), goodsId, stealTempData.getUserId(), num, System.currentTimeMillis());
                LogMgr.addLogBusyFarmingSteal(stealLog);

            }
        }

        //记录偷取过的玩家
        if(stealTempData.getUserId() > 10) {
            stolenUserMap.put(stealTempData.getUserId(), DateHelper.getCurrentSecond());
        }

        //本服处理失窃记录
        if(stealUserData != null){
            UserBaseInfo userBaseInfo = UserMgr.getUserBaseInfo(player.getUserId(), GameServer.getInstance().getServerId());
            BusyFarmingLand land = stealUserData.getLandMap().get(landId);
            BusyFarmingMgr.dealReduction(stealUserData, land, goodsId, player.getUserId(), userBaseInfo, num);
        }

        BusyFarmingProto.BusyFarmingStealRespMsg.Builder respMsg = BusyFarmingProto.BusyFarmingStealRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setLandId(landId);
        respMsg.setReward(PropertyHelper.parsePropertyToString(reward));
        player.sendPacket(Protocol.U_BUSY_FARMING_STEAL, respMsg);
        return 0;
    }

    /**
     * 卖水果
     */
    public int sellingFruit() {

        BusyFarmingUserData userData = BusyFarmingMgr.getBusyFarmingUserData(player.getUserId());
        if(userData == null){
            return GameErrorCode.E_BUSY_FARMING_ACTIVITY_NO_UNLOCK;
        }

        //获取四类道具的数量
        BagModule bagModule = player.getModule(BagModule.class);
        Map<Integer, Long> allGoodsMap = new HashMap<>();
        List<BusyFarmingProto.BusyFarmingSellingFruitResultTemp> builderList = new ArrayList<>();
        synchronized (userData){
            Property consume = new Property();
            for(int goodsId : BusyFarmingMgr.getBusyFarmingFruitGoods()){
                UserBagItem userBagItem = bagModule.getUserBagItem(goodsId);
                if(userBagItem != null && userBagItem.getNum() > 0){
                    allGoodsMap.put(goodsId, userBagItem.getNum());
                    consume.addProperty(goodsId, BigInteger.valueOf(userBagItem.getNum()));
                }
            }
            if(consume.isNothing()){
                return GameErrorCode.E_BUSY_FARMING_ACTIVITY_NO_FRUIT_TO_SELLING;
            }

            Property reward = new Property();
            for(int goodsId : allGoodsMap.keySet()){
                GoodsInfo goodsInfo = GoodsMgr.getGoodsById(goodsId);
                if(goodsInfo != null){
                   long score = goodsInfo.getParamList().get(0).intValue() * allGoodsMap.get(goodsId);
                   //增加水果币
                   reward.addProperty(BusyFarmingMgr.BUSY_FARMING_FRUIT_SCORE_ID, BigInteger.valueOf(score));
                   BusyFarmingProto.BusyFarmingSellingFruitResultTemp.Builder builder = BusyFarmingProto.BusyFarmingSellingFruitResultTemp.newBuilder();
                   builder.setId(goodsId);
                   builder.setNum(allGoodsMap.get(goodsId).intValue());
                   builder.setScoreNum((int)score);
                   builderList.add(builder.build());
                }
            }
            if(!player.getModule(CurrencyModule.class).removeCurrency(consume, eLogMoneyType.BusyFarmingActivity, eLogMoneyType.BusyFarmingActivitySellingGoods)){
                return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
            }

            player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.BusyFarmingActivity, eLogMoneyType.BusyFarmingActivityGetScoreGoods);
        }

        BusyFarmingProto.BusyFarmingSellingFruitRespMsg.Builder respMsg = BusyFarmingProto.BusyFarmingSellingFruitRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.addAllReward(builderList);
        player.sendPacket(Protocol.U_BUSY_FARMING_SELLING_FRUIT, respMsg);
        return 0;
    }

    /**
     * 领奖期间-自动收获-售卖水果道具
     */
    public int harvestInRewardPeriod(){
        BusyFarmingUserData userData = BusyFarmingMgr.getBusyFarmingUserData(player.getUserId());
        if(userData == null){
            return GameErrorCode.E_BUSY_FARMING_ACTIVITY_NO_UNLOCK;
        }
        Property reward = new Property();
        boolean harvest = false;
        log.info("start auto harvest user {} land", player.getUserId());
        synchronized (userData) {
            for (BusyFarmingLand land : userData.getLandMap().values()) {
                if (land.getGoodsId() == 0) {
                    continue;
                }
                GoodsInfo fruit = BusyFarmingMgr.getSeedMaturityFruit(land.getGoodsId());
                int num = BusyFarmingMgr.getSeedMaturityFruitNum(land.getGoodsId(), land.getWateringTimes());
                //减产
                for(int c : land.getReduce()){
                    num -= c;
                }
                //收获水果
                reward.addProperty(fruit.getGoodsId(), BigInteger.valueOf((long)num));
                land.getStates().clear();
                land.getStates().add(eBusyFarmingLandState.Plant.getIntValue());
                clearLandData(land);
                harvest = true;
            }
            if(harvest){
                //收获水果
                player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.BusyFarmingActivity, eLogMoneyType.BusyFarmingActivityGetGoods);
                userData.setUpdateOption();
                log.info("user {} harvest {}", player.getUserId(), PropertyHelper.parsePropertyToString(reward));
            }
            //自动卖水果
            reward = new Property();
            BagModule bagModule = player.getModule(BagModule.class);
            Property consume = new Property();
            for(int goodsId : BusyFarmingMgr.getBusyFarmingFruitGoods()){
                UserBagItem userBagItem = bagModule.getUserBagItem(goodsId);
                if(userBagItem != null && userBagItem.getNum() > 0){
                    consume.addProperty(goodsId, BigInteger.valueOf(userBagItem.getNum()));
                    GoodsInfo goodsInfo = GoodsMgr.getGoodsById(goodsId);
                    if(goodsInfo != null) {
                        long score = BigDecimal.valueOf(goodsInfo.getParamList().get(0).longValue()).multiply(BigDecimal.valueOf(userBagItem.getNum())).multiply(
                                BigDecimal.valueOf(BusyFarmingMgr.BUSY_FARMING_RECOVERY_DISCOUNT)).divide(BigDecimal.valueOf(1000),0, BigDecimal.ROUND_UP).longValue();
                        reward.addProperty(BusyFarmingMgr.BUSY_FARMING_FRUIT_SCORE_ID, BigInteger.valueOf(score));
                    }
                }
            }
            if(!player.getModule(CurrencyModule.class).removeCurrency(consume, eLogMoneyType.BusyFarmingActivity, eLogMoneyType.BusyFarmingActivitySellingGoods)){
                return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
            }
            log.info("user {} auto selling {}", player.getUserId(), PropertyHelper.parsePropertyToString(consume));
            //增加水果币
            player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.BusyFarmingActivity, eLogMoneyType.BusyFarmingActivityGetScoreGoods);
            log.info("user {} auto get fruit score {}", player.getUserId(), PropertyHelper.parsePropertyToString(reward));
        }
        return 0;
    }

    /**
     * 删除酬谢（已领取的）
     */
    public int delFriendReward() {
        BusyFarmingUserData userData = BusyFarmingMgr.getBusyFarmingUserData(player.getUserId());
        if(userData == null){
            return GameErrorCode.E_BUSY_FARMING_ACTIVITY_NO_UNLOCK;
        }

        List<BusyFarmingUserReward> rewardList = BusyFarmingMgr.getUserReward(player.getUserId());
        if(rewardList != null && rewardList.size() > 0){
            synchronized (userData){
                Iterator<BusyFarmingUserReward> iterator = rewardList.iterator();
                while (iterator.hasNext()){
                    BusyFarmingUserReward reward = iterator.next();
                    if(reward.isDel() || !reward.isGetReward()){
                        continue;
                    }
                    reward.setDel(true);
                }
            }
        }else {

        }
        BusyFarmingProto.BusyFarmingDelFriendRewardRespMsg.Builder respMsg = BusyFarmingProto.BusyFarmingDelFriendRewardRespMsg.newBuilder();
        respMsg.setRet(0);
        if(rewardList != null) {
            List<BusyFarmingProto.BusyFarmingUserRewardTemp> builderList = BusyFarmingPb.getBusyFarmingUserRewardTemps(rewardList);
            respMsg.addAllReward(builderList);
        }
        player.sendPacket(Protocol.U_BUSY_FARMING_FRIEND_DEL_REWARD, respMsg);
        return 0;
    }

    /**
     * 本服偷取查找逻辑
     */
    public int stealSearch() {
        BusyFarmingUserData userData = BusyFarmingMgr.getBusyFarmingUserData(player.getUserId());
        int grade = userData.getHomeGrade();
        int gradeRange = BusyFarmingMgr.getBusyFarmingStolenParam().get(0);
        //随机结果
        List<BusyFarmingUserData> result = new ArrayList<>();
        //临时玩家
        Set<Long> userIdList = new HashSet<>();
        for(long uid : BusyFarmingMgr.getUserDataMap().keySet()){
            userIdList.add(uid);
        }
        userIdList.remove(player.getUserId());
        //移除亲家
        Map<Long, RelativesInfo> relativesInfoMap = player.getModule(RelativesModule.class).getRelativesMap();
        for(Map.Entry<Long, RelativesInfo> entry : relativesInfoMap.entrySet()){
            RelativesInfo relativesInfo = entry.getValue();
            if(relativesInfo.getStatus() == 1) {
                userIdList.remove(entry.getKey());
            }
        }
        //移除被偷玩家
        userIdList.removeAll(getStolenUser());
        //移除盟友
        Map<Long, CrossUnionMember> memberMap = CrossUnionMgr.getUnionMemberMap(player.getUserInfo().getUnionUid());
        if(memberMap != null){
            userIdList.removeAll(memberMap.keySet());
        }
        //待随机集合
        List<BusyFarmingUserData> tempList = new ArrayList<>();
        random(grade, gradeRange, userIdList, tempList);

        //不限制等级范围，重随机一遍
        if(tempList.size() < 3){
            List<BusyFarmingUserData> tempList2 = new ArrayList<>();
            random(grade, 100, userIdList, tempList2);
            while (tempList.size() < 3 && tempList2.size() > 0){
                Random random = new Random();
                int idx = random.nextInt(tempList2.size());
                tempList.add(tempList2.get(idx));
                tempList2.remove(idx);
            }
        }

        if(tempList.size() < 3){
            //return GameErrorCode.E_BUSY_FARMING_ACTIVITY_STEAL_USER_NO_ENOUGH;
            result.addAll(tempList);
        }else {
            Random random = new Random();
            for (int i = 0; i < 3; i++) {
                int idx = random.nextInt(tempList.size());
                result.add(tempList.get(idx));
                tempList.remove(idx);
            }
        }
        List<BusyFarmingProto.CrossBusyFarmingStealDataTemp> list = new ArrayList<>();
        for(BusyFarmingUserData data : result){
            BusyFarmingProto.CrossBusyFarmingStealDataTemp.Builder builder = BusyFarmingProto.CrossBusyFarmingStealDataTemp.newBuilder();
            builder.setUserId(data.getUserId());
            builder.setServerId(GameServer.getInstance().getServerId());
            builder.setGrade(data.getHomeGrade());
            UserBaseInfo baseInfo = UserMgr.parseUserBaseInfo(UserMgr.getUserInfo(data.getUserId()), GameServer.getInstance().getServerId());
            builder.setUserBaseInfo(PlayerBasePb.parsePlayerBaseTempMsg(baseInfo));
            BusyFarmingProto.BusyFarmingUserDataTemp.Builder dataBuilder = BusyFarmingPb.getUserDataBuilder(data, true);
            builder.addAllLand(dataBuilder.getLandList());
            list.add(builder.build());
        }
        return initStealCacheData(userData, list, BusyFarmingMgr.getShowTimeActivityId());
    }

    public void random(int grade, int gradeRange, Set<Long> userIdList, List<BusyFarmingUserData> tempList) {
        Iterator<Long> iterator = userIdList.iterator();
        int max = grade + gradeRange;
        int min = Math.max(1, grade - gradeRange);
        while (iterator.hasNext()){
            long userId = iterator.next();
            BusyFarmingUserData tempUserData = BusyFarmingMgr.getBusyFarmingUserData(userId);
            if(tempUserData != null && tempUserData.getHomeGrade() <= max && tempUserData.getHomeGrade() >= min){
                if(BusyFarmingMgr.landHasState(tempUserData, eBusyFarmingLandState.Steal.getIntValue())){
                    tempList.add(tempUserData);
                    iterator.remove();
                }
            }
        }
    }

    /**
     * 初始来助记录
     */
    private BusyFarmingHelpRecord initHelpRecord(long userId, UserInfo friendUserInfo, int seedId, int addition) {
        BusyFarmingHelpRecord record;
        record = new BusyFarmingHelpRecord();
        record.setActivityId(BusyFarmingMgr.getShowTimeActivityId());
        record.setUserId(userId);
        record.setFriendId(friendUserInfo.getUserId());
        record.setHelpType(1);
        record.setHelpTime(DateHelper.getCurrentSecond());
        record.getParams().add(String.valueOf(friendUserInfo.getTitleId()));
        record.getParams().add(friendUserInfo.getNickName());
        GoodsInfo goodsInfo = BusyFarmingMgr.getSeedMaturityFruit(seedId);
        String language = friendUserInfo.getLanguage();
        UserInfo userInfo = UserMgr.getUserInfo(userId);
        if(userInfo != null){
            language = userInfo.getLanguage();
        }
        record.getParams().add(ServerLanguageMgr.getContent(goodsInfo.getGoodsName(), language));
        record.getParams().add(String.valueOf(addition));
        record.setInsertOption();
        return record;
    }

    /**
     * 初始浇水酬谢(水果数量奖励)
     */
    private BusyFarmingUserReward initUserReward(UserInfo friendUserInfo, long userId, int seedId) {
        BusyFarmingUserReward reward;
        reward = new BusyFarmingUserReward();
        reward.setActivityId(BusyFarmingMgr.getShowTimeActivityId());
        reward.setUserId(userId);
        reward.setAddTime(DateHelper.getCurrentSecond());
        reward.setFriendId(friendUserInfo.getUserId());
        reward.setHelpType(1);
        reward.getParams().add(String.valueOf(friendUserInfo.getTitleId()));
        reward.getParams().add(friendUserInfo.getNickName());
        GoodsInfo goodsInfo = BusyFarmingMgr.getSeedMaturityFruit(seedId);
        reward.getParams().add(ServerLanguageMgr.getContent(goodsInfo.getGoodsName(), player.getUserInfo().getLanguage()));
        int num = BusyFarmingMgr.getWateringRewardFruitNum(seedId, BusyFarmingMgr.getBusyFarmingWateringParam().get(2));
        reward.setReward(goodsInfo.getGoodsId() + "=" + num);
        reward.setInsertOption();
        return reward;
    }

    /**
     * 初始浇水酬谢(水果数量奖励)
     */
    private BusyFarmingUserReward initUserReward(UserBaseInfo friend, long friendId, long userId, int seedId) {
        BusyFarmingUserReward reward;
        reward = new BusyFarmingUserReward();
        reward.setActivityId(BusyFarmingMgr.getShowTimeActivityId());
        reward.setUserId(userId);
        reward.setAddTime(DateHelper.getCurrentSecond());
        reward.setFriendId(friendId);
        reward.setHelpType(1);
        reward.getParams().add(String.valueOf(friend.getTitleId()));
        reward.getParams().add(friend.getNickName());
        GoodsInfo goodsInfo = BusyFarmingMgr.getSeedMaturityFruit(seedId);
        reward.getParams().add(ServerLanguageMgr.getContent(goodsInfo.getGoodsName(), player.getUserInfo().getLanguage()));
        int num = BusyFarmingMgr.getWateringRewardFruitNum(seedId, BusyFarmingMgr.getBusyFarmingWateringParam().get(2));
        reward.setReward(goodsInfo.getGoodsId() + "=" + num);
        reward.setInsertOption();
        return reward;
    }

    /**
     * 初始偷菜
     */
    public int initStealCacheData(BusyFarmingUserData userData, List<BusyFarmingProto.CrossBusyFarmingStealDataTemp> list, int activityId){

        //请求详情的验证码
        int STEAL_CSRF_CODE;
        synchronized (userData){
            if(userData.getStealTimes() >= BusyFarmingMgr.getBusyFarmingStolenParam().get(1)){
                return GameErrorCode.E_BUSY_FARMING_ACTIVITY_STEAL_NO_TIMES;
            }
            Random random = new Random();

            BusyFarmingModule busyFarmingModule = player.getModule(BusyFarmingModule.class);
            //缓存相关数据
            STEAL_CSRF_CODE = random.nextInt(100000) + 1;
            busyFarmingModule.GOTO_STEAL_DETAIL_CSRF_CODE = STEAL_CSRF_CODE;
            //缓存随机的结果
            busyFarmingModule.stealSearchTempList = list;
            //清除上次偷取的缓存
            busyFarmingModule.stealTempData = null;


            //当前玩家土地解锁个数
            int landNum = 0;
            for(BusyFarmingLand land : userData.getLandMap().values()){
                if(!land.getStates().contains(eBusyFarmingLandState.Lock.getIntValue())){
                    landNum++;
                }
            }
            int numRange = BusyFarmingMgr.getBusyFarmingRobotGardenRange().get(1);
            int max = Math.min(landNum + numRange, BusyFarmingMgr.ALL_LAND_NUM);
            int min = Math.max(BusyFarmingMgr.UN_LOCKED_LAND_NUM, landNum - numRange);
            int matureNum = randomHelper.next(min, max + 1);

            //不足随机补充机器人
            for(int i = list.size(); i < 3; i++){
                BusyFarmingProto.CrossBusyFarmingStealDataTemp dataTemp = randomRobot(userData, i + 1, matureNum, matureNum, player.getLanguage());
                list.add(dataTemp);
            }

            //增加已偷次数
            userData.setStealTimes(1 + userData.getStealTimes());
        }

        BusyFarmingProto.CrossBusyFarmingStealSearchRespMsg.Builder respMsg = BusyFarmingProto.CrossBusyFarmingStealSearchRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setActivityId(activityId);
        respMsg.addAllSteal(list);
        respMsg.setCsrf(STEAL_CSRF_CODE);
        player.sendPacket(Protocol.U_BUSY_FARMING_STEAL_SEARCH, respMsg);
        return 0;
    }

    /**
     * 随机玩家果园
     * @param unLock  土地解锁
     * @param matureNum  可偷取数量
     */
    private BusyFarmingProto.CrossBusyFarmingStealDataTemp randomRobot(BusyFarmingUserData userData, long userId, int unLock, int matureNum, String language) {
        BusyFarmingProto.CrossBusyFarmingStealDataTemp.Builder builder = BusyFarmingProto.CrossBusyFarmingStealDataTemp.newBuilder();
        if(BusyFarmingMgr.getActivityInfo() == null){
            return builder.build();
        }
        //userId < 4  为机器人
        builder.setUserId(userId);
        List<Long> serverList = BusyFarmingMgr.getActivityInfo().getServerIdList();
        builder.setServerId(serverList.get(randomHelper.next(0, serverList.size())));

        //当前玩家果园等级
        int grade = userData.getHomeGrade();
        int gradeRange = BusyFarmingMgr.getBusyFarmingRobotGardenRange().get(0);
        int max = grade + gradeRange;
        int min = Math.max(1, grade - gradeRange);
        List<Integer> gradeList = new ArrayList<>();
        for(BusyFarmingGradeInfo gradeInfo : BusyFarmingMgr.getGradeInfoList()){
            if(gradeInfo.getId() >= min && gradeInfo.getId() <= max){
                gradeList.add(gradeInfo.getId());
            }
        }
        //随机机器人果园等级
        int gradeIdx = randomHelper.next(0, gradeList.size());
        builder.setGrade(gradeList.get(gradeIdx));

        //baseInfo
        PlayerProto.PlayerBaseTempMsg.Builder baseInfoTemp = PlayerProto.PlayerBaseTempMsg.newBuilder();
        eSexType sexType = eSexType.parse(randomHelper.next(1, 3));
        baseInfoTemp.setSex(sexType.getValue());
        baseInfoTemp.setNickName(NameMgr.getRandomName(sexType, language));
        baseInfoTemp.setDecoration(DecorationMgr.getDefaultDecoration(sexType.getValue()));
        baseInfoTemp.setServerId(builder.getServerId());
        if(!BusyFarmingMgr.isCrossBusyFarmingActivity()){
            baseInfoTemp.setTitleId(randomHelper.next(1, TitleMgr.getMaxTitleId()));
            LocationInfo locationInfo = LocationMgr.getDefaultLocation(language);
            baseInfoTemp.setCity(locationInfo.getCity());
        }
        builder.setUserBaseInfo(baseInfoTemp);
        //land
        for(int i = 0; i < BusyFarmingMgr.ALL_LAND_NUM; i++) {
            BusyFarmingLand land = new BusyFarmingLand();
            land.setId(i);
            if(i > unLock - 1){
                land.getStates().add(eBusyFarmingLandState.Lock.getIntValue());
            }else {
                if(i < matureNum){
                    int seedIdx = randomHelper.next(0, BusyFarmingMgr.getBusyFarmingSeedGoods().size());
                    land.setGoodsId(BusyFarmingMgr.getBusyFarmingSeedGoods().get(seedIdx));
                    land.setHarvestTime(0);
                    land.setTotalTime(0);
                    land.getStates().add(eBusyFarmingLandState.Harvest.getIntValue());
                    land.getStates().add(eBusyFarmingLandState.Steal.getIntValue());
                    land.setFlorescence(false);
                }else {
                    land.getStates().add(eBusyFarmingLandState.Plant.getIntValue());
                }
            }
            builder.addLand(BusyFarmingPb.getLandBuilder(land));
        }
        return builder.build();
    }

    /**
     * 下发红点
     * help:1;stolen:2;reward:4;harvest:8
     */
    public void syncRedDot(int type, int val){
        BusyFarmingProto.BusyFarmingRedDotSyncMsg.Builder builder = BusyFarmingProto.BusyFarmingRedDotSyncMsg.newBuilder();
        if((1 & type) == 1){
            builder.setHelp(1 & val);
        }
        if((2 & type) == 2){
            builder.setStolen(2 & val);
        }
        if((4 & type) == 4){
            builder.setReward(4 & val);
        }
        if((8 & type) == 8){
            builder.setHarvest(8 & val);
        }
        player.sendPacket(Protocol.U_BUSY_FARMING_RED_DOT_SYNC, builder);
    }

    /**
     * 获取5分钟内被偷过的玩家
     */
    public List<Long> getStolenUser(){
        List<Long> result = new ArrayList<>();
        int currentSecond = DateHelper.getCurrentSecond();
        int min5 = 60 * 5;
        Iterator<Long> iterator = stolenUserMap.keySet().iterator();
        while (iterator.hasNext()){
            long userId = iterator.next();
            if(currentSecond - stolenUserMap.get(userId) < min5){
                result.add(userId);
            }else {
                iterator.remove();
            }
        }
        return result;
    }

    /**
     * 跨服浇水
     */
    public int crossWatering(int landId, long userServerId, long userId) {

        List<Integer> wateringParams = BusyFarmingMgr.getBusyFarmingWateringParam();
        BusyFarmingUserData userData = BusyFarmingMgr.getBusyFarmingUserData(player.getUserId());
        //我的浇水次数
        if(userData.getWateringTimes() >= wateringParams.get(0)){
            return GameErrorCode.E_BUSY_FARMING_ACTIVITY_WATERING_HAD_LIMIT;
        }

        BusyFarmingProto.BusyFarmingWateringCrossReqMsg.Builder crossReq = BusyFarmingProto.BusyFarmingWateringCrossReqMsg.newBuilder();
        crossReq.setActivityId(BusyFarmingMgr.getShowTimeActivityId());
        crossReq.setLandId(landId);
        crossReq.setServerId(userServerId);
        crossReq.setUserId(userId);
        crossReq.setSrcServerId(GameServer.getInstance().getServerId());
        crossReq.setSrcUserId(player.getUserId());

        UserBaseInfo baseInfo = UserMgr.getUserBaseInfo(player.getUserId(), GameServer.getInstance().getServerId());
        crossReq.setUserBaseInfo(PlayerBasePb.parsePlayerBaseTempMsg(baseInfo));

        player.sendPacket(Protocol.C_BUSY_FARMING_WATERING, crossReq);
        return 0;
    }

    /**
     * 跨服查看家园详情
     */
    public int crossFriendHomeDetail(long userServerId, long userId) {

        BusyFarmingProto.BusyFarmingFriendHomeDetailCrossReqMsg.Builder crossReq = BusyFarmingProto.BusyFarmingFriendHomeDetailCrossReqMsg.newBuilder();
        crossReq.setActivityId(BusyFarmingMgr.getShowTimeActivityId());
        crossReq.setServerId(userServerId);
        crossReq.setUserId(userId);
        crossReq.setSrcUserId(player.getUserId());
        crossReq.setSrcServerId(GameServer.getInstance().getServerId());
        //判定浇水次数，强制设置成不可浇水
        BusyFarmingUserData myData = getUserData();
        if(myData != null){
            crossReq.setCanWatering(!(myData.getWateringTimes() >= BusyFarmingMgr.getBusyFarmingWateringParam().get(0)));
            player.sendPacket(Protocol.C_BUSY_FARMING_FRIEND_HOME_DETAIL, crossReq);
        }

        return 0;
    }

}
